<?php
namespace Admin\Controller;
use Think\Controller;

class LoginController extends Controller{
    //展示登录页面的模板
    public function index(){
        $this->display();
    }
    //处理登录页面
    public function doLogin(){
        $loginarr = ['status' => 0, 'mess' => '登录失败!','data' => ''];
    	if(IS_AJAX){
            $userName = I('post.username/s','');
            //相当于后台处理的check.php $username =$_POST['username'];进行过滤默认的是htmlspcialchar
            $passWord = I('post.password/s','','strip_tags');
            $is_match = preg_match('/^[A-Za-z0-9]+$/', $userName);
			if(empty($userName)){
                $loginarr['mess'] = '用户名不能为空';
                exit(json_encode($loginarr));
            }
            if(!$is_match){
                $loginarr['mess'] = '用户名不合法';
                exit(json_encode($loginarr));
            }
            if(empty($passWord)){
                $loginarr['mess'] = '密码不能为空';
                exit(json_encode($loginarr));
            }
            $mysql = M('admin');
            $mysqlInfo = $mysql-> field('id,name,pwd,realname') -> where(['status' => 1,'name'=>$userName]) -> find();
            if(is_null($mysqlInfo)){
                $loginarr['mess'] = $userName.'用户名不存在';
                exit(json_encode($loginarr));
            }
            if($mysqlInfo['pwd'] == _md5($passWord)){ 
                $mysql->execute('update dx_admin set loginnum = loginnum + 1,logintime = "'._getDate().'",ip= "'.get_client_ip().'" where id='.$mysqlInfo['id']);
                //登录成功后先让次数加一   
            }else{
                $loginarr['mess'] = '密码错误';
                exit(json_encode($loginarr));
            }
            session('user',[
                'uid' => $mysqlInfo['id'], 
                'account' => $mysqlInfo['name'], 
                'realname'=> $mysqlInfo['realname']
                ]);
            $loginarr['status'] = 1;
            $loginarr['mess'] = '登录成功';
    	}
    	echo json_encode($loginarr);
    }

    public function Loginout(){
        //session(null);tp自带的session销毁方法
        $_SESSION = [];
        $this -> redirect('login/index');

    }


}



